import { IResponse, iup } from '../../util';
import { NGLang, wfAlert } from './util';

//审批界面获取工作流信息返回内容
export interface WorkFlowHisData {
  taskId: string; //任务id
  procInstId: string; //流程实例id
  parentTaskId: string; // 父任务id
  bizOperation: string; //业务操作
  bizApproved: boolean; //是否审批
  preRollbackBizCheck: boolean; //回退操作前要进行业务校验，用于在只能本人进行补偿的表单操作，进行补偿前检测
  multiInstanceTask: boolean; //是否会签
  initiateUserTask: boolean; // 是否是流程发起节点
  mustUploadBizAttachment: boolean; //是否必须上传单据附
  mustUploadApprovalAttachment: boolean; // 是否必须上传审批附件
  allowCarbonCopy: boolean; // 是否允许抄送
}

/**
 * 审批界面获取工作流信息
 * @param wfPiId
 * @param wfTaskId
 * @param wfOType
 */
export async function getWorkFlowInfo({ wfPiId, wfTaskId, wfOType, copyId, nodeDefKey }) {
  const taskDefKey = copyId ? nodeDefKey : ''; //在抄送的查阅情况下 跳转过来的链接带有copyId的情况下用nodeDefKey来代替taskId查询信息
  const { code, message, data } = await iup.request.body({
    url: 'workflow/task/getTaskExecutionInfo',
    data: { procInstId: wfPiId, taskId: wfTaskId, wfotype: wfOType, taskDefKey }
  });
  if (code === 0) {
    return data || {};
  } else {
    await wfAlert(NGLang.alertTitle, message || NGLang.paramError);
  }
}

/**
 * 获取流程历史
 * @param procInstId
 */
export async function getWorkFlowHis({ procInstId }) {
  const { code, message, data } = await iup.request.body({
    url: 'workflow/process/getProcessComments',
    data: { procInstId }
  });
  if (code === 0) {
    return data || [];
  } else {
    await wfAlert(NGLang.getFlowHisError, message);
    return [];
  }
}

/**
 * 获取常用语关键词
 */
export async function getCommonWordHelp() {
  const resp = await iup.request.get({
    url: 'workflow/content/getCommonContents'
  });
  if (resp?.code === 0) {
    return resp.data;
  } else {
    return [];
  }
}
/**
 * 创建-更新常用语
 * @param content
 * @param id
 */
export async function createOrUpdateContent(content, id?) {
  const resp = await iup.request.body({
    url: 'workflow/content/createOrUpdateContent',
    data: {
      content,
      id
    }
  });
  if (resp?.code === 0) {
    return resp;
  } else {
    await wfAlert(NGLang.alertTitle, NGLang.paramError);
    return resp;
  }
}

/**
 * 常用语删除
 * @param contentId
 */
export async function deleteContentById(contentIds) {
  const resp = await iup.request.body({
    url: 'workflow/content/deleteContentById',
    data: {
      contentIds
    }
  });
  if (resp?.code === 0) {
    return true;
  } else {
    await wfAlert(NGLang.alertTitle, resp?.message);
    return false;
  }
}

/**
 * 获取签章数据源
 */
export async function getSignatureListByCurrentUser() {
  const resp: any = await iup.request.get({
    url: 'WM/Archive/WmIoSignature/GetSignatureListByCurrentUser'
  });
  if (resp.Record && resp.Record.length) {
    return resp.Record.map((d) => {
      return {
        value: d.PhId,
        label: d.Cname,
        origin: {
          ...d,
          MarkPath: d.MarkPath ? iup.getHttpUrl(d.MarkPath) : ''
        }
      };
    });
  }
  return [];
}

/**
 * 验证签章信息
 * @param PhId
 * @param pwd
 */
export async function validSignatureInfoByPassword({ PhId, pwd }) {
  const resp: any = await iup.request.get({
    url: 'WM/Archive/WmIoSignature/GetSignatureInfogByPassword',
    data: {
      id: PhId,
      password: pwd
    }
  });
  return !!(resp.Record && resp.Record.length);
}

export function updateNotificationReadFlg({ piId }) {
  iup.request
    .get({
      url: 'WorkFlow3/ProcessNotification/UpdateNotificationReadFlg',
      data: { piid: piId }
    })
    .then();
}

/**
 * 保存审批意见区宽度
 * @param width 意见区宽度
 * @constructor
 */
export function saveRemarkPanelWidth(width) {
  if (width <= 0) {
    return;
  }
  // iup.request
  //   .get({
  //     data: { width },
  //     url: 'WorkFlow3/WorkFlow/SaveRemarkPanelWidth'
  //   })
  //   .then();
}

/**
 * 获取发起节点属性
 * @param processDefinitionId 流程Id
 * @constructor 获取是否签章和最少意见数，原来是放在流程定义列表里面的，现在单独一个接口来获取。
 */
export async function getProcessInitialActivity(processDefinitionId) {
  const resp = await iup.request.get({
    data: { processDefinitionId },
    url: 'workflow/processDefinition/getProcessInitialActivity'
  });
  if (resp.code === 0) {
    return resp.data;
  } else {
    return {};
  }
}

export async function checkPreStartProcessInstance(params) {
  let resp = await iup.request.body({
    data: { ...params },
    url: 'workflow/process/checkPreStartProcessInstance'
  });
  return resp;
}

export async function checkPreRollback(taskId) {
  let resp = await iup.request.get({
    data: { taskId },
    url: 'workflow/task/checkPreRollback'
  });
  return resp;
}

/**
 * 获取回退信息
 * @param taskId 任务id
 */
export async function getRollBackInfo(taskId) {
  const resp = await iup.request.get({
    url: 'workflow/task/getRollbackExecutionInfo',
    data: { taskId }
  });
  if (resp.code === 0) {
    return resp.data;
  }
}

export async function RollBack(params) {
  const resp = await iup.request.body({
    url: 'workflow/task/rollback',
    data: { ...params }
  });
  if (resp.code) {
    return resp;
  } else {
    return resp;
  }
}

/**
 * 加签
 * @param params 包含任务id
 */
export async function addSubTaskAsync(params) {
  const resp = await iup.request.body({
    url: 'workflow/task/addSubTasks',
    data: { ...params }
  });
  return resp;
}

//前置检查
export async function checkPreCompleteTask(taskId) {
  let resp = await iup.request.get({
    data: { taskId },
    url: `workflow/task/checkPreCompleteTask?taskId=${taskId}`
  });
  return resp;
}
//任务完成
export async function compeleteTask(params) {
  const resp = await iup.request.body({
    url: 'workflow/task/completeTask',
    data: { ...params }
  });
  return resp;
}

interface CarbonCopyResponse<T> extends IResponse {
  data: T;
}
/** @description  抄送*/
export async function carbonCopy(taskId: string, userNos: string[], appCode = '0100') {
  const resp = await iup.request.body<CarbonCopyResponse<{ data: boolean }>>({
    url: '/workflow/copy/carbonCopy',
    data: {
      userNos,
      taskId,
      appCode
    }
  });
  return resp;
}
//获取待办信息
export async function getToDoInfo(taskId) {
  const resp = await iup.request.get({
    url: `workflow/task/getToDoInfo?taskId=${taskId}`
  });
  if (resp.code === 0) {
    return resp.data;
  } else {
    await wfAlert(NGLang.getFlowHisError, resp.message);
    return null;
  }
}

/**
 * @description 获取已办节点信息
 */
export async function getCompletedNodeInfo(params) {
  const resp = await iup.request.get({
    url: `workflow/task/getCompletedNodeInfo`,
    data: {
      pageNum: params.pageIndex,
      pageSize: params.pageSize,
      taskId: params.taskId
    }
  });
  if (resp.code === 0) {
    return resp.data;
  } else {
    return null;
  }
}

/**
 * @description 获取待办节点信息
 */
export async function getUnHandledNodeInfo(params) {
  const resp = await iup.request.get({
    url: `workflow/task/getUnHandledNodeInfo`,
    data: {
      pageNum: params.pageIndex,
      pageSize: params.pageSize,
      taskId: params.taskId
    }
  });
  if (resp.code === 0) {
    return resp.data;
  } else {
    return null;
  }
}

export async function getSignatureByUser() {
  const res = await iup.request.get({
    url: '/workflow/signature/getSignatureByUser'
  });
  if (res.code === 0) {
    return res.data;
  } else {
    return undefined;
  }
}

/**
 * @description 获取下一人工任务节点
 */
export async function getNextUserTaskNodes(taskId) {
  const res = await iup.request.get({
    url: `/workflow/task/getNextUserTaskNodes?taskId=${taskId}`
  });
  if (res.code === 0) {
    return res.data;
  } else {
    return undefined;
  }
}
